package tk.mybatis.springboot.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class WxUtils {
    private static final String APPID = "wxc20fa2f8d06c2cf3";
    private static final String SECRET = "84e498b33774d1d9af0a40d8be8a429a";
    private static final String API_URL = "https://api.weixin.qq.com/sns/jscode2session";

    public static String getOpenid(String code) {
        try {
            // 构建请求 URL
            String requestUrl = API_URL + "?appid=" + APPID + "&secret=" + SECRET + "&js_code=" + code + "&grant_type=authorization_code";
            URL url = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            // 获取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            // 解析响应，获取 openid
            String responseStr = response.toString();
            if (responseStr.contains("openid")) {
                int startIndex = responseStr.indexOf("\"openid\":\"") + "\"openid\":\"".length();
                int endIndex = responseStr.indexOf("\"", startIndex);
                return responseStr.substring(startIndex, endIndex);
            }
        } catch (Exception e) {
            System.out.println("获取用户id失败:" + e.getMessage());
        }
        return null;
    }

    public static void main(String[] args) {
        String code = "your_code";
        String openid = getOpenid(code);
        System.out.println("OpenID: " + openid);
    }
}
